<template>
  <!--引用表格-->
  <BasicTable @register="registerTable" :rowSelection="rowSelection">
    <!-- <template #tableSidebar>
        <LeftTree ref="leftTree" @select="onTreeSelect" @root-tree-data="onRootTreeData" />
      </template> -->

    <!--插槽:table标题-->
    <template #tableTitle>
      <a-button
        type="primary"
        v-auth="'projectproposalpreparation:project_proposal_preparation:add'"
        @click="handleAdd"
        preIcon="ant-design:plus-outlined"
      >
        新增
      </a-button>
      <a-button
        v-auth="'projectproposalpreparation:project_proposal_preparation:exportXls'"
        preIcon="ant-design:export-outlined"
        @click="onExportXls"
      >
        导出
      </a-button>
      <j-upload-button
        v-auth="'projectproposalpreparation:project_proposal_preparation:importExcel'"
        preIcon="ant-design:import-outlined"
        @click="onImportXls"
        >导入
      </j-upload-button>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <template #overlay>
          <a-menu>
            <a-menu-item :disabled="batchDelDisabled" key="1" @click="batchHandleDelete">
              <Icon icon="ant-design:delete-outlined"></Icon>
              删除
            </a-menu-item>
          </a-menu>
        </template>
        <a-button v-auth="'projectproposalpreparation:project_proposal_preparation:deleteBatch'"
          >批量操作
          <Icon icon="mdi:chevron-down"></Icon>
        </a-button>
      </a-dropdown>
      <!-- 高级查询 -->
      <super-query :config="superQueryConfig" @search="handleSuperQuery" />
    </template>
    <!--操作栏-->
    <template #action="{ record }">
      <TableAction divider :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)" />
    </template>
    <!--字段回显插槽-->
    <template v-slot:bodyCell="{ column, record, index, text }">
      <template v-if="column.dataIndex === 'attachmentInfo'">
        <!--文件字段回显插槽-->
        <span v-if="!text" style="font-size: 12px; font-style: italic">无文件</span>
        <a-button v-else :ghost="true" type="primary" preIcon="ant-design:download-outlined" size="small" @click="downloadFile(text)">下载 </a-button>
      </template>
      <template v-if="column.dataIndex === 'otherRecordAttachments'">
        <!--文件字段回显插槽-->
        <span v-if="!text" style="font-size: 12px; font-style: italic">无文件</span>
        <a-button v-else :ghost="true" type="primary" preIcon="ant-design:download-outlined" size="small" @click="downloadFile(text)">下载 </a-button>
      </template>
    </template>
  </BasicTable>
  <!-- 表单区域 -->
  <!-- <ProjectProposalPreparationModal @register="registerModal" @success="handleSuccess"></ProjectProposalPreparationModal> -->

  <BasicModal
    v-bind="$attrs"
    wrapClassName="approval-form-modal"
    :destroyOnClose="true"
    :footer="null"
    :title="approvalModal.title"
    :width="896"
    :canFullscreen="true"
    :defaultFullscreen="true"
    @register="registerApprovalModal"
  >
    <ProjectProposalPreparationApproval
      :isInModal="true"
      :formBpm="false"
      :formDisabled="approvalModal.disabled"
      :recordId="approvalModal.recordId"
      :processInstanceId="approvalModal.processInstanceId"
      :processStatus="approvalModal.processStatus"
      :operate="approvalModal.operate"
      :isApprovalNew="approvalModal.isApprovalNew"
      @success="handleSuccess"
    ></ProjectProposalPreparationApproval>
  </BasicModal>
</template>

<script lang="ts" name="projectproposalpreparation-projectProposalPreparation" setup>
  import { ref, reactive, computed, unref } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { useListPage } from '/@/hooks/system/useListPage';
  import { useModal } from '/@/components/Modal';
  import ProjectProposalPreparationModal from './components/ProjectProposalPreparationModal.vue';
  import { columns, searchFormSchema, superQuerySchema } from './ProjectProposalPreparation.data';
  import { list, deleteOne, batchDelete, getImportUrl, getExportUrl } from './ProjectProposalPreparation.api';
  import { downloadFile } from '/@/utils/common/renderUtils';
  import { useUserStore } from '/@/store/modules/user';
  import { BasicModal } from '/@/components/Modal';
  import ProjectProposalPreparationApproval from './ProjectProposalPreparationApproval.vue';
  import { usePermission } from '/@/hooks/web/usePermission';

  const { hasPermission } = usePermission();
  const deletePermission = computed(() => hasPermission('projectproposalpreparation:project_proposal_preparation:delete'));
  const editPermission = computed(() => hasPermission('projectproposalpreparation:project_proposal_preparation:edit'));

  const approvalModal = ref<any>({
    title: '新增',
    operate: '',
    recordId: '',
    processInstanceId: '',
    processStatus: '',
    disabled: false,
    isApprovalNew: 0,
  });

  const queryParam = reactive<any>({});
  const checkedKeys = ref<Array<string | number>>([]);
  const userStore = useUserStore();
  //注册model
  const [registerApprovalModal, { openModal, closeModal }] = useModal();
  //注册table数据
  const { prefixCls, tableContext, onExportXls, onImportXls } = useListPage({
    tableProps: {
      title: '项目立项编制主表',
      api: list,
      columns,
      canResize: false,
      formConfig: {
        //labelWidth: 120,
        schemas: searchFormSchema,
        autoSubmitOnEnter: true,
        showAdvancedButton: true,
        fieldMapToNumber: [],
        fieldMapToTime: [],
      },
      actionColumn: {
        // width: 120,
        // fixed: 'right',
      },
      beforeFetch: (params) => {
        return Object.assign(params, queryParam);
      },
    },
    exportConfig: {
      name: '项目立项编制主表',
      url: getExportUrl,
      params: queryParam,
    },
    importConfig: {
      url: getImportUrl,
      success: handleSuccess,
    },
  });

  const [registerTable, { reload }, { rowSelection, selectedRowKeys, selectedRows }] = tableContext;

  // 高级查询配置
  const superQueryConfig = reactive(superQuerySchema);

  /**
   * 高级查询事件
   */
  function handleSuperQuery(params) {
    Object.keys(params).map((k) => {
      queryParam[k] = params[k];
    });
    reload();
  }

  /**
   * 新增事件
   */
  function handleAdd() {
    approvalModal.value.title = '新增';
    approvalModal.value.operate = 'create';
    approvalModal.value.disabled = false;
    approvalModal.value.recordId = '';
    approvalModal.value.processInstanceId = '';
    approvalModal.value.processStatus = '';
    approvalModal.value.taskId = '';
    approvalModal.value.isApprovalNew = new Date().getTime();

    openModal(true, {
      isUpdate: false,
      showFooter: true,
    });
  }

  /**
   * 编辑事件
   */
  function handleEdit(record: Recordable) {
    approvalModal.value.title = '编辑';
    approvalModal.value.operate = 'edit';
    approvalModal.value.disabled = false;
    approvalModal.value.recordId = record.id;
    approvalModal.value.processInstanceId = record.processInstanceId;
    approvalModal.value.processStatus = record.processStatus;
    approvalModal.value.isApprovalNew = new Date().getTime();

    openModal(true, {
      record,
      isUpdate: true,
      showFooter: true,
    });
  }

  /**
   * 详情
   */
  function handleDetail(record: Recordable) {
    approvalModal.value.title = '查看';
    approvalModal.value.operate = 'view';
    approvalModal.value.disabled = true;
    approvalModal.value.recordId = record.id;
    approvalModal.value.processInstanceId = record.processInstanceId;
    approvalModal.value.processStatus = record.processStatus;
    approvalModal.value.isApprovalNew = new Date().getTime();

    openModal(true, {
      record,
      isUpdate: true,
      showFooter: false,
    });
  }

  /**
   * 删除事件
   */
  async function handleDelete(record) {
    await deleteOne({ id: record.id }, handleSuccess);
  }

  // 批量删除按钮状态
  const batchDelDisabled = computed(() => {
    let disabled = selectedRows.value.some((item: any) => {
      return item.processStatus !== 'DRAFT';
    });
    if (!disabled) {
      disabled = !deletePermission.value;
    }
    return disabled;
  });

  /**
   * 批量删除事件
   */
  async function batchHandleDelete() {
    await batchDelete({ ids: selectedRowKeys.value }, handleSuccess);
  }

  /**
   * 成功回调
   */
  function handleSuccess() {
    closeModal();
    (selectedRowKeys.value = []) && reload();
  }

  /**
   * 操作栏
   */
  function editBtnDisabled(record: any) {
    let disabled = record.processStatus !== 'DRAFT';
    if (!disabled) {
      const userId = userStore.getUserInfo.id;
      if (userId !== record.createBy) {
        disabled = true;
      }
    }
    if(!disabled){
      disabled = !editPermission.value
    }
    return disabled;
  }
  function getTableAction(record) {
    return [
      {
        label: '编辑',
        onClick: handleEdit.bind(null, record),
        color: 'success',
        disabled: editBtnDisabled(record),
        useConfirmButton: false,
        auth: 'projectproposalpreparation:project_proposal_preparation:edit',
      },
    ];
  }

  /**
   * 下拉操作栏
   */
  function getDropDownAction(record) {
    return [
      {
        label: '详情',
        onClick: handleDetail.bind(null, record),
        color: 'info',
        type: 'link',
        size: 'small',
        useConfirmButton: false,
      },
      {
        label: '删除',
        popConfirm: {
          title: '是否确认删除',
          confirm: handleDelete.bind(null, record),
          placement: 'topLeft',
        },
        disabled: record.processStatus !== 'DRAFT',
        type: 'link',
        size: 'small',
        color: 'error',
        useConfirmButton: true,
        auth: 'projectproposalpreparation:project_proposal_preparation:delete',
      },
    ];
  }
</script>

<style lang="less" scoped>
  :deep(.ant-picker),
  :deep(.ant-input-number) {
    width: 100%;
  }

  :deep(.basictable-sidebar) {
    height: calc(100vh - 40px - 60px - 64px - 36px);
  }

  .approval-form-modal {
    /** 时间和数字输入框样式 */
    :deep(.ant-input-number) {
      width: 100%;
    }

    :deep(.ant-calendar-picker) {
      width: 100%;
    }
  }
</style>
